package day12.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class StudentDaoImpl implements StudentDao {
    @Override
    public List<Student> queryAll() {
        List<Student> students = new ArrayList<>();
        SAXReader reader = new SAXReader();
        try {
            // 通过reader对象的read方法加载books.xml文件,获取docuemnt对象。
            Document document = reader.read(new File("src\\main\\resources\\students.xml"));
            // 通过document对象获取根节点bookstore
            Element bookStore = document.getRootElement();
//            List<Element> els = bookStore.elements("student");
            // 通过element对象的elementIterator方法获取迭代器
            Iterator it = bookStore.elementIterator();
            // 遍历迭代器，获取根节点中的信息（书籍）
            while (it.hasNext()) {
                Student student = new Student();
                Element Student = (Element) it.next();
                student.setName(Student.elementText("name"));
                student.setPassword(Student.elementText("password"));
                student.setSex(Student.elementText("sex"));
                student.setAge(Student.elementText("age"));
                student.setClazz(Student.elementText("clazz"));
                students.add(student);
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return students;
    }
}
